package com.itheima.filters;


import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AdminAuthorizeFilter implements GlobalFilter , Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

       //1.1获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //1.2获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        //2.获取请求过来的url地址
        String path = request.getURI().getPath();
        System.out.println("请求的地址"+path);



        //3.判断地址是否是后台的登录地址
        if (path.startsWith("/admin/login")){
            //4.是就放行
            return chain.filter(exchange);
        }

        //自己写的
        /* if (path.startsWith("/admin/channel/update")){
            //放行
            return  chain.filter(exchange);
        }*/


        //1.token校验
        //1.1获取token
        String token = request.getHeaders().getFirst("token");
        //2.非空判断
        if (!StringUtils.isEmpty(token)){
            //3.验证token
            int verifyToken = AppJwtUtil.verifyToken(token);

            if (SystemConstants.JWT_OK==verifyToken) {
                //4.验证通过则放行
                return chain.filter(exchange);
               }
         }

        //5. 没有token，或验证没通过的，阻止请求。响应未登录
        response.setStatusCode(HttpStatus.UNAUTHORIZED);

        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
